//
//  ListViewController.m
//  yinsiwenzhen
//
//  Created by Yangfan on 14/12/24.
//  Copyright (c) 2014年 4gread. All rights reserved.
//
/**
 *  单元格上显示的内容包含：病图、问诊时间（提交病情询问的时间）、病情简短的描述、处理情况
 */
#import "ListViewController.h"
#import "ListTableViewCell.h"
#import "ListDetailViewController.h"

@interface ListViewController ()

@end

@implementation ListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    UILabel *navLabel = [[UILabel alloc] initWithFrame:CGRectMake(50, 0, kScreen_Width-100, 44)];
//    navLabel.text = @"问诊记录";
//    navLabel.textColor = [UIColor blackColor];
//    navLabel.font = [UIFont systemFontOfSize:18];
//    navLabel.textAlignment = NSTextAlignmentCenter;
//    self.navigationItem.titleView = navLabel;
    
    
    
    self.title = @"问诊记录";
    [self.navigationController.navigationBar
     setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                             [UIColor colorWithRed:0.44 green:0.44 blue:0.44 alpha:1], NSForegroundColorAttributeName,
                             [UIFont systemFontOfSize:20],
                             NSFontAttributeName,nil]];
    
    
    // Do any additional setup after loading the view.
    _indexPaths = [[NSArray alloc] init];
//    [self getListData];
    [self initListUI];
}
- (void)viewWillAppear:(BOOL)animated {
    if (!connectionNetFlag) {// 没有连接网络
        [self showAlertView];
    }else{
        [self getListData];
        [_listTableView reloadData];
    }
    [super viewWillAppear:animated];
}

-(void)initListUI{
    _listTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, 320, self.view.frame.size.height)];
    _listTableView.backgroundColor = [UIColor whiteColor];
    _listTableView.rowHeight = 56;
    _listTableView.delegate = self;
    _listTableView.dataSource = self;
    _listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;// 去掉表中的分割线
    [self.view addSubview:_listTableView];
}

// 获取AVOS里面的数据
-(void)getListData{
    [self showIndeterminateProgress]; // 请求网络的菊花圈
    _diseaseArray = [[NSMutableArray alloc] initWithCapacity:0];
    _timeArray = [[NSMutableArray alloc] initWithCapacity:0];
    _manageArray = [[NSMutableArray alloc] initWithCapacity:0];
    _objectIdArray = [[NSMutableArray alloc] initWithCapacity:0];
    _allObjects =[[NSMutableArray alloc] initWithCapacity:0];
    // 获取识别用户的Id ：myString
    NSUserDefaults *userDefaultes = [NSUserDefaults standardUserDefaults];
    NSString *myString = [userDefaultes stringForKey:@"personage"];// 获取本地数据
    
    AVQuery *disease = [AVQuery queryWithClassName:@"equipmentId"];
    AVObject *summary = [disease getObjectWithId:myString];
    AVRelation *detail = [summary relationforKey:@"diseaseRelation"];
    [[detail query] findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            
        } else {
            _allObjects = [NSMutableArray arrayWithArray:objects];
            if (_allObjects.count>0) {
                for (int i = _allObjects.count-1 ; i >=0 ; i--) {
                    AVObject *diseases = [_allObjects objectAtIndex:i];
                    [_timeArray addObject:diseases.createdAt];
                    [_objectIdArray addObject:diseases.objectId];
                    [_manageArray addObject:[diseases objectForKey:@"whetherPharmacy"]];
                }
                [_listTableView reloadData];

            }else{
                _listAlertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您还没有添加任何数据哦" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [NSTimer scheduledTimerWithTimeInterval:2.0f target:self selector:@selector(performDismiss:) userInfo:nil repeats:NO];
                [_listAlertView show];
            }
            
        }
    }];

    [HUD hide:YES];
    
}
// 定时器的方法 没有数据 则直接回到主页面
-(void)performDismiss:(NSTimer *)timer{
    [_listAlertView dismissWithClickedButtonIndex:0 animated:NO];
    [self.navigationController popToRootViewControllerAnimated:YES];
}
#pragma mark-----UITableViewCell-----------
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    NSLog(@"****%d", [_allObjects count]);
    return [_allObjects count];
//    NSLog(@"%@",_allObjects);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static  NSString *cellIdentifier = @"Cell";
    
    ListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[ListTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }
    else{
        while ([cell.contentView.subviews lastObject] != nil) {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
  
    cell.lineImage.frame = CGRectMake(0, 51, kScreen_Width, 5);
    cell.selectionStyle = UITableViewCellAccessoryNone;
    
    NSData *data = [_timeArray objectAtIndex:indexPath.row];
    NSString *timeString = [NSString stringWithFormat:@"%@",data];
    NSString *timeStr = [timeString substringWithRange:NSMakeRange(11,2)];
    NSString *timeStrings = [timeString substringWithRange:NSMakeRange(0,10)];//  截取中鼎范围内的字符串 NSMakeRange(排行第几位,共几位)
    int intString = [timeStr intValue];
    NSString *timeString1 = [timeString substringWithRange:NSMakeRange(13,3)];
    cell.timeLab.text = [NSString stringWithFormat:@"%@  %d%@",timeStrings,intString+8,timeString1];
//    NSLog(@"----------%@",_manageArray);
     if ([[_manageArray objectAtIndex:indexPath.row] boolValue] == 0) {// 已处理
         [cell.recordButton setBackgroundImage:[UIImage imageNamed:@"image_chuli"] forState:UIControlStateNormal];
         cell.timeLab.textColor = [UIColor colorWithRed:0.41 green:0.77 blue:0.95 alpha:1];
         cell.recordButton.backgroundColor = [UIColor colorWithRed:0.41 green:0.77 blue:0.95 alpha:1];
     }else{// 未处理
         cell.timeLab.textColor = [UIColor colorWithRed:0.27 green:0.27 blue:0.27 alpha:1];
     }
    
    if (isiphone6plus) {
        cell.timeLab.font = [UIFont systemFontOfSize:22];
        
    } else if(isiphone4){
        cell.timeLab.font = [UIFont systemFontOfSize:16];
    }else {
         cell.timeLab.font = [UIFont systemFontOfSize:18];
        
    }
    return cell;
}
// 点击单元格
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    ListDetailViewController *list = [[ListDetailViewController alloc] init];
    list.objectIdStr = [_objectIdArray objectAtIndex:indexPath.row];
    [self.navigationController pushViewController:list animated:YES];
}
//划动cell是否出现del按钮
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}
//设定横向滑动时是否出现删除按扭,（阻止第一行出现）
-(UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}
// 编辑单元格（左移 删除功能）
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        _cellIndex = indexPath.row;
        _indexPaths = [NSArray arrayWithObject:indexPath];
        _dataAlertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您确定要删除您的这条病例信息吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        [_dataAlertView show];
    }
   

}
// 改变 把左划“删除” 改成 “粉碎”
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"粉碎";
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    switch (buttonIndex) {
        case 0:{
//            NSLog(@"您现在点击了：“取消”的按钮");
        }
            break;
        case 1:{
            
            if (_allObjects.count > 0) {
                // 删除数组中的数据
                [_allObjects removeObjectAtIndex:_cellIndex];// 从数组中删除这一条数据
                [_listTableView deleteRowsAtIndexPaths:_indexPaths withRowAnimation:UITableViewRowAnimationLeft];// 删除这一行
                 [_listTableView reloadData];// 刷新表

                // 删除AVOS里面的数据
                AVQuery *disease = [AVQuery queryWithClassName:@"diseaseRecord"];
                AVObject *allobject = [disease getObjectWithId:[_objectIdArray objectAtIndex:_cellIndex]];
                [_objectIdArray removeObjectAtIndex:_cellIndex];
                [allobject delete];
                
            }

        }
            
            break;
            
        default:
            break;
    }
}
// 定时器的方法
//-(void)performDismiss:(NSTimer *)timer{
//
//    [_dataAlertView dismissWithClickedButtonIndex:0 animated:NO];
//
//}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
